class EquipmentManager {
    constructor() {
        this.currentUser = null;
        this.equipmentList = [];
        this.userBookings = [];
        this.filteredEquipment = [];
        this.categories = [];
        this.updateInterval = null;
    }

    async initialize() {
        this.currentUser = await this.getCurrentUser();
        await this.loadCategories();
        await this.loadEquipment();
        await this.loadUserBookings();
        this.setupEventListeners();

        // 设置默认日期为今天
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('bookingDate').value = today;

        // 开始实时更新
        this.startRealTimeUpdates();
    }

    // 实时更新
    startRealTimeUpdates() {
        this.updateInterval = setInterval(() => {
            this.updateUpdateTime();
        }, 30000);

        this.updateUpdateTime();
    }

    // 更新最后更新时间
    updateUpdateTime() {
        const now = new Date();
        const timeString = now.toLocaleTimeString('zh-CN');
        document.getElementById('updateTime').textContent = timeString;
    }

    // 选择特定道具
    selectEquipment(equipmentId) {
        const equipment = this.equipmentList.find(item => item.id === equipmentId);
        if (equipment) {
            document.getElementById('equipmentName').value = equipmentId;
            document.getElementById('selectedEquipmentId').value = equipmentId;
            this.calculateCost();
            document.querySelector('.booking-form').scrollIntoView({
                behavior: 'smooth'
            });
        }
    }

    async getCurrentUser() {
        try {
            // 优先使用全局状态中的用户信息
            if (AppState.currentUser) {
                return AppState.currentUser;
            }

            // 降级到本地存储
            const storedUser = localStorage.getItem('currentUser');
            if (storedUser) {
                return JSON.parse(storedUser);
            }

            // 最后尝试从API获取
            const userData = await userService.getProfile('current');
            return userData.user || null;
        } catch (error) {
            console.error('Failed to get current user:', error);
            return null;
        }
    }

    async loadCategories() {
        try {
            this.categories = await getEquipmentCategories();
            this.renderCategories();
        } catch (error) {
            console.error('Failed to load categories:', error);
            this.categories = [];
            this.renderCategories();
        }
    }

    async loadEquipment() {
        console.log('🔄 开始加载道具列表...');
        try {
            this.equipmentList = await getAvailableEquipment();
            console.log('✅ 获取到的道具数据:', this.equipmentList);
            console.log('📦 道具数量:', this.equipmentList.length);
            this.filteredEquipment = [...this.equipmentList];
            this.renderEquipmentGrid();
            this.populateEquipmentSelect();
        } catch (error) {
            console.error('❌ 加载道具失败:', error);
            console.error('❌ 错误详情:', error.message);
            console.error('❌ 错误堆栈:', error.stack);
            this.equipmentList = [];
            this.filteredEquipment = [];
            this.renderEquipmentGrid();
            this.populateEquipmentSelect();
        }
    }

    async loadUserBookings() {
        try {
            const userId = this.currentUser?.id;
            if (userId) {
                this.userBookings = await getUserBookings(userId);
                this.renderBookingsList();
            }
        } catch (error) {
            console.error('Failed to load bookings:', error);
            this.userBookings = [];
            this.renderBookingsList();
        }
    }

    setupEventListeners() {
        const form = document.getElementById('equipmentBookingForm');
        if (form) {
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                this.submitBooking();
            });
        }

        const equipmentSelect = document.getElementById('equipmentName');
        if (equipmentSelect) {
            equipmentSelect.addEventListener('change', () => {
                this.calculateCost();
            });
        }

        const quantityInput = document.getElementById('quantity');
        if (quantityInput) {
            quantityInput.addEventListener('input', () => {
                this.calculateCost();
            });
        }

        const startTimeInput = document.getElementById('startTime');
        if (startTimeInput) {
            startTimeInput.addEventListener('change', () => {
                this.validateTimeRange();
            });
        }

        const endTimeInput = document.getElementById('endTime');
        if (endTimeInput) {
            endTimeInput.addEventListener('change', () => {
                this.validateTimeRange();
            });
        }

        this.showPriorityIndicator();
    }

    // 显示高优先级游客标识
    showPriorityIndicator() {
        const priorityIndicator = document.getElementById('priorityIndicator');
        if (priorityIndicator && this.currentUser && this.currentUser.priority === 'high') {
            priorityIndicator.style.display = 'block';
        }
    }

    renderCategories() {
        const container = document.querySelector('.equipment-categories');
        if (!container) return;

        // 清空现有按钮（保留全部道具按钮）
        const allBtn = container.querySelector('[data-category="all"]');
        container.innerHTML = '';
        if (allBtn) {
            container.appendChild(allBtn);
        }

        // 添加分类按钮
        this.categories.forEach(category => {
            const button = document.createElement('button');
            button.className = 'category-btn';
            button.setAttribute('data-category', category.id);
            button.textContent = category.name;
            button.addEventListener('click', () => this.filterByCategory(category.id));
            container.appendChild(button);
        });
    }

    renderEquipmentGrid() {
        const grid = document.getElementById('equipmentGrid');
        if (!grid) return;

        console.log('🎨 开始渲染道具网格...');
        console.log('📦 过滤后的道具数量:', this.filteredEquipment.length);
        console.log('📦 过滤后的道具:', this.filteredEquipment);

        grid.innerHTML = '';

        if (this.filteredEquipment.length === 0) {
            console.warn('⚠️ 没有可用道具，显示提示信息');
            grid.innerHTML = '<p style="text-align: center; color: #666; grid-column: 1 / -1;">暂无可用道具</p>';
            return;
        }

        this.filteredEquipment.forEach(equipment => {
            const card = document.createElement('div');
            card.className = 'equipment-card';

            const availabilityPercent = (equipment.availableQuantity / equipment.totalQuantity) * 100;
            let availabilityClass = 'high';
            if (availabilityPercent < 30) availabilityClass = 'low';
            else if (availabilityPercent < 60) availabilityClass = 'medium';

            card.innerHTML = `
                <div class="equipment-image">
                    <span>${equipment.icon || '🎯'}</span>
                </div>
                <div class="equipment-info">
                    <div class="equipment-name">${equipment.name}</div>
                    <span class="equipment-category">${equipment.categoryName}</span>
                    <p class="equipment-description">${equipment.description}</p>
                    <div class="equipment-details">
                        <div class="detail-item">
                            <div class="detail-label">时租</div>
                            <div class="detail-value">¥${equipment.hourlyRate}</div>
                        </div>
                        <div class="detail-item">
                            <div class="detail-label">押金</div>
                            <div class="detail-value">¥${equipment.deposit}</div>
                        </div>
                        <div class="detail-item">
                            <div class="detail-label">库存</div>
                            <div class="detail-value ${availabilityClass}">${equipment.availableQuantity}/${equipment.totalQuantity}</div>
                        </div>
                    </div>
                    <div class="equipment-actions">
                        <button class="btn btn-secondary" onclick="equipmentManager.viewDetails('${equipment.id}')">查看详情</button>
                        <button class="btn btn-primary" onclick="equipmentManager.selectForBooking('${equipment.id}')" 
                                ${equipment.availableQuantity === 0 ? 'disabled' : ''}>
                            ${equipment.availableQuantity === 0 ? '已租完' : '立即预约'}
                        </button>
                    </div>
                </div>
            `;

            grid.appendChild(card);
        });
    }

    populateEquipmentSelect() {
        const select = document.getElementById('equipmentName');
        if (!select) return;

        // 清空现有选项（保留第一个提示选项）
        while (select.options.length > 1) {
            select.remove(1);
        }

        this.equipmentList.forEach(equipment => {
            const option = document.createElement('option');
            option.value = equipment.id;
            option.textContent = `${equipment.name} (${equipment.availableQuantity > 0 ? '可租借' : '已租完'})`;
            option.disabled = equipment.availableQuantity === 0;
            select.appendChild(option);
        });
    }

    renderBookingsList() {
        const list = document.getElementById('bookingsList');
        if (!list) return;

        list.innerHTML = '';

        if (this.userBookings.length === 0) {
            list.innerHTML = '<p style="text-align: center; color: #999;">暂无租赁记录</p>';
            return;
        }

        this.userBookings.forEach(booking => {
            const item = document.createElement('div');
            item.className = 'booking-item';

            item.innerHTML = `
                <div class="booking-info">
                    <h5>${booking.equipmentName}</h5>
                    <div class="booking-meta">
                        <span>${booking.bookingDate}</span>
                        <span>${booking.startTime} - ${booking.endTime}</span>
                        <span>数量: ${booking.quantity}</span>
                    </div>
                    ${booking.specialRequirements ? `<p class="booking-requirements">特殊要求: ${booking.specialRequirements}</p>` : ''}
                </div>
                <div class="booking-status status-${booking.status}">
                    ${this.getStatusText(booking.status)}
                </div>
                <div class="booking-actions">
                    ${booking.status === 'CONFIRMED' || booking.status === 'PENDING' ? `
                    <button class="btn btn-sm btn-danger" onclick="equipmentManager.cancelBooking('${booking.id}')">取消</button>
                    ` : ''}
                </div>
            `;

            list.appendChild(item);
        });
    }

    getStatusText(status) {
        const statusMap = {
            'PENDING': '待确认',
            'CONFIRMED': '已确认',
            'CANCELLED': '已取消',
            'COMPLETED': '已完成',
            'IN_USE': '使用中'
        };
        return statusMap[status] || status;
    }

    filterByCategory(categoryId) {
        // 更新按钮状态
        document.querySelectorAll('.category-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-category="${categoryId}"]`).classList.add('active');

        if (categoryId === 'all') {
            this.filteredEquipment = [...this.equipmentList];
        } else {
            this.filteredEquipment = this.equipmentList.filter(item => item.categoryId === categoryId);
        }

        this.renderEquipmentGrid();
    }

    selectForBooking(equipmentId) {
        this.selectEquipment(equipmentId);
    }

    viewDetails(equipmentId) {
        const equipment = this.equipmentList.find(item => item.id === equipmentId);
        if (equipment) {
            const details = `
${equipment.name}

描述: ${equipment.description}
时租: ¥${equipment.hourlyRate}/小时
押金: ¥${equipment.deposit}
当前库存: ${equipment.availableQuantity}/${equipment.totalQuantity}
分类: ${equipment.categoryName}

${equipment.availableQuantity > 0 ? '✅ 可立即租借' : '❌ 暂时缺货'}
            `;
            alert(details);
        }
    }

    calculateCost() {
        const equipmentId = document.getElementById('equipmentName').value;
        const quantity = parseInt(document.getElementById('quantity').value) || 1;

        if (!equipmentId) {
            document.getElementById('costPreview').style.display = 'none';
            return;
        }

        const equipment = this.equipmentList.find(item => item.id === equipmentId);
        if (!equipment) return;

        const startTime = document.getElementById('startTime').value;
        const endTime = document.getElementById('endTime').value;

        let hours = 1;
        if (startTime && endTime) {
            const start = new Date(`2000-01-01T${startTime}`);
            const end = new Date(`2000-01-01T${endTime}`);
            const diffMs = end - start;
            hours = Math.max(1, Math.ceil(diffMs / (1000 * 60 * 60)));
        }

        const rentalCost = equipment.hourlyRate * hours * quantity;
        const depositCost = equipment.deposit * quantity;
        const totalCost = rentalCost + depositCost;

        document.getElementById('rentalCost').textContent = `¥${rentalCost}`;
        document.getElementById('depositCost').textContent = `¥${depositCost}`;
        document.getElementById('totalCost').textContent = `¥${totalCost}`;

        document.getElementById('costPreview').style.display = 'block';
    }

    validateTimeRange() {
        const startTime = document.getElementById('startTime').value;
        const endTime = document.getElementById('endTime').value;

        if (startTime && endTime) {
            const start = new Date(`2000-01-01T${startTime}`);
            const end = new Date(`2000-01-01T${endTime}`);

            if (end <= start) {
                Utils.showNotification('结束时间必须晚于开始时间', 'warning');
                document.getElementById('endTime').value = '';
            }
        }

        this.calculateCost();
    }

    async submitBooking() {
        const formData = {
            equipmentId: document.getElementById('equipmentName').value,
            bookingDate: document.getElementById('bookingDate').value,
            startTime: document.getElementById('startTime').value,
            endTime: document.getElementById('endTime').value,
            quantity: parseInt(document.getElementById('quantity').value),
            userId: this.currentUser?.id || 'guest_' + Date.now(), // 🔥 添加 userId 字段
            specialRequirements: document.getElementById('specialRequirements').value
        };

        if (!this.validateForm(formData)) {
            return;
        }

        try {
            const result = await bookEquipment(formData);
            Utils.showNotification('道具预约成功！', 'success');

            // 重新加载数据
            await this.loadEquipment();
            await this.loadUserBookings();

            // 清空表单
            this.clearForm();

        } catch (error) {
            console.error('Equipment booking failed:', error);
            Utils.showNotification('预约失败，请重试', 'error');
        }
    }

    validateForm(formData) {
        if (!formData.equipmentId) {
            Utils.showNotification('请选择要预约的道具', 'error');
            return false;
        }

        if (!formData.bookingDate) {
            Utils.showNotification('请选择使用日期', 'error');
            return false;
        }

        if (!formData.startTime || !formData.endTime) {
            Utils.showNotification('请选择使用时间', 'error');
            return false;
        }

        const selectedDate = new Date(formData.bookingDate);
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        if (selectedDate < today) {
            Utils.showNotification('不能选择过去的日期', 'error');
            return false;
        }

        if (formData.quantity < 1) {
            Utils.showNotification('数量必须大于0', 'error');
            return false;
        }

        // 检查库存
        const equipment = this.equipmentList.find(item => item.id === formData.equipmentId);
        if (equipment && formData.quantity > equipment.availableQuantity) {
            Utils.showNotification(`库存不足，当前仅剩 ${equipment.availableQuantity} 件`, 'error');
            return false;
        }

        return true;
    }

    async cancelBooking(bookingId) {
        if (!confirm('确定要取消这个预约吗？')) {
            return;
        }

        try {
            await cancelBooking(bookingId);
            Utils.showNotification('预约已取消', 'success');

            // 重新加载数据
            await this.loadEquipment();
            await this.loadUserBookings();

        } catch (error) {
            console.error('Cancel booking failed:', error);
            Utils.showNotification('取消失败，请重试', 'error');
        }
    }

    clearForm() {
        const form = document.getElementById('equipmentBookingForm');
        if (form) form.reset();
        document.getElementById('costPreview').style.display = 'none';

        // 重置日期为今天
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('bookingDate').value = today;
    }

    // 清理资源
    destroy() {
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
        }
    }
}

// 初始化
const equipmentManager = new EquipmentManager();
document.addEventListener('DOMContentLoaded', () => {
    equipmentManager.initialize();
});

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
    equipmentManager.destroy();
});